package com.example.crawlerjava.service.crawler.core;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.example.crawlerjava.config.CrawlerConfig;
import com.example.crawlerjava.config.NcatConfig;
import com.example.crawlerjava.service.crawler.CrawlerStrategy;
import com.example.crawlerjava.entity.NcatEntity;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.ServiceWorkerPolicy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service("ncatCrawler")
public class NcatCrawlerImpl implements CrawlerStrategy<NcatEntity> {
    @Resource
    private CrawlerConfig crawlerConfig;
    @Resource
    private NcatConfig ncatConfig;
    /**
     * 搜索
     */
    private static final String BASE_SEARCH = "/search?os=pc&k=";

    @Override
    public List<NcatEntity> search(String searchKey) {
        String searchUrl = ncatConfig.getBaseUrl() + BASE_SEARCH + searchKey;

        String response = HttpUtil.get(searchUrl, 5000);
        log.info("searchUrl:{},response:{}", searchUrl, response);
        // 解析HTML文档
        Document doc = Jsoup.parse(response);

        Elements select = doc.select(".search-result-list > .search-result-item");
        if (ObjectUtil.isEmpty(select)) {
            return Collections.emptyList();
        }
        List<NcatEntity> entities = new ArrayList<>();
        for (Element element : select) {
            log.info("element:{}", element.attr("href"));
            Elements selected = element.select(".search-result-item-main > .title");
            Element title = selected.get(0);
            String text = title.text();
            NcatEntity ncatEntity = new NcatEntity();
            ncatEntity.setSourceUrl(ncatConfig.getBaseUrl() + element.attr("href"));
            ncatEntity.setSourceName(text);
            Elements image = element.select(".search-result-item-side > .search-result-item-pic > img");
            ncatEntity.setSourceCover(ncatConfig.getCdnUrl() + image.attr("data-original"));
            entities.add(ncatEntity);
        }

        return entities;
    }

    @Override
    public NcatEntity getDetail(String detailUrl) {

        try (Playwright playwright = Playwright.create()) {
            BrowserType chromium = playwright.chromium();


            Path userDataDir = Paths.get(ncatConfig.getSaveFile());
            BrowserType.LaunchPersistentContextOptions options = new BrowserType.LaunchPersistentContextOptions();
            options.setChannel("msedge");

            //这里代表是否要可视化，false代表可视化，true代表非可视化
            if (crawlerConfig.getOpenView()) {
                options.setHeadless(false);
                options.setViewportSize(1920, 1080);
            } else {
                options.setHeadless(true);
            }
            options.setAcceptDownloads(true)
                    .setJavaScriptEnabled(true)
                    .setBypassCSP(true);

            BrowserContext browserContext = chromium.launchPersistentContext(userDataDir, options);

            browserContext.route("**/disable-devtool/**", Route::abort);

            browserContext.setDefaultTimeout(30000);

            Page page = browserContext.newPage();
            page.navigate(detailUrl);

            //默认十秒等待
            Page.WaitForRequestOptions requestOptions = new Page.WaitForRequestOptions();
            requestOptions.setTimeout(10000);


            Request request = page.waitForRequest(waitForRequest -> waitForRequest.url().contains("index.m3u8"),
                    () -> System.out.println("下载地址"));
            NcatEntity ncatEntity = new NcatEntity();
            ncatEntity.setSourceCover("");
            ncatEntity.setSourceName("");
            ncatEntity.setSourceUrl(request.url());
            return ncatEntity;
        } catch (Exception e) {
            log.error("获取下载地址异常:", e);
        }
        return null;
    }

    @Override
    public String getDownloadUrl(String downloadUrl) {
        return null;
    }
}
